package com.zytlifeservice.service.pay;

import com.qianmi.open.api.ApiException;
import com.qianmi.open.api.domain.elife.AirSeat;
import com.qianmi.open.api.domain.elife.Airline;
import com.qianmi.open.api.domain.elife.Station;
import com.qianmi.open.api.request.AirItemsListRequest;
import com.qianmi.open.api.request.AirLinesListRequest;
import com.qianmi.open.api.request.AirOrderCreateRequest;
import com.qianmi.open.api.request.AirStationsListRequest;
import com.qianmi.open.api.response.AirItemsListResponse;
import com.qianmi.open.api.response.AirLinesListResponse;
import com.qianmi.open.api.response.AirOrderCreateResponse;
import com.qianmi.open.api.response.AirStationsListResponse;
import com.zytlifeservice.domain.Result;
import com.zytlifeservice.domain.User;
import com.zytlifeservice.domain.pay.*;
import com.zytlifeservice.exception.UserException;
import com.zytlifeservice.repository.UserRepository;
import com.zytlifeservice.repository.pay.AirplaneRechargeOrderRepository;
import com.zytlifeservice.repository.pay.AlipayOrderRepository;
import com.zytlifeservice.repository.pay.WxPayOrderRepository;
import com.zytlifeservice.util.Base64Utils;
import com.zytlifeservice.util.ResultUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 飞机票业务类
 * Created by Administrator on 2017/6/3.
 */
@Service
public class AirplaneService {

    @Autowired
    PublicService publicService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    AlipayOrderRepository alipayOrderRepository;

    @Autowired
    AirplaneRechargeOrderRepository airplaneRechargeOrderRepository;

    @Autowired
    AlipayService alipayService;

    @Autowired
    WxPayService wxPayService;

    @Autowired
    WxPayOrderRepository wxPayOrderRepository;

    private String itemId;

    public String findItemId() throws ApiException {
        System.out.println("进入飞机查询itemId方法");
        AirItemsListRequest req = new AirItemsListRequest();
        AirItemsListResponse response = publicService.execute(req);
        if (null != response.getItems() && response.getItems().size() > 0) {
            return response.getItems().get(0).getItemId();
        } else {
            return null;
        }
    }

    public Result findAirplaneCity() throws ApiException {
        System.out.println("进入航班城市查询");
        AirStationsListRequest req = new AirStationsListRequest();
        AirStationsListResponse response = publicService.execute(req);
        List<Station> stationsList = response.getStations();
        if (null != stationsList && stationsList.size() > 0) {
            return ResultUtil.success(stationsList, "成功");
        } else {
            return ResultUtil.error(-1, "该城市暂时未开通服务");
        }
    }

    //查询航线信息
    public Result findLines(String from, String to, String fromDate, Integer currtePage) throws Exception {
        System.out.println("进入航班信息查询方法");
        List<Airplane> airplaneList = new ArrayList<Airplane>();
        int start = 0;
        int end = 0;//分页处理
        int pageSize = 20;//页数大小
        List<Airline> airlinesLists = oddAirplane(from, fromDate, to);
        if (airlinesLists == null) {
            throw new UserException("未查询到航班信息", 303);
        }
        int listSize = airlinesLists.size();//集合长度
        int totalPage = listSize / 20;
        if (currtePage <= totalPage) {
            if (currtePage == 0) {
                start = 0;
                end = 19;
            } else {
                start = currtePage * 20;
                end = (currtePage + 1) * 20 - 1;
            }
        }
        if (totalPage >= currtePage) {
            //说明有数据，在这里返回客户端数据
            if (null != airlinesLists) {
                if (currtePage == 0) {
                    for (int i = start; i < airlinesLists.size(); i++) {
                        Airline airline = airlinesLists.get(i);
                        List<AirSeat> seatList = airline.getAirSeats();//舱位集合
                        for (AirSeat airSeat : seatList) {
                            Airplane airplane = null;
                            if (airplaneList.size() < pageSize && airSeat.getSeatStatus() != null && airSeat.getSettlePrice() != null && airSeat.getSeatCode() != null && airSeat.getDiscount() != null && airSeat.getSeatMsg() != null) {
                                airplane = new Airplane();
                                airplane.setAdultAirportTax(airline.getAdultAirportTax());
                                airplane.setAdultFuelTax(airline.getAdultFuelTax());
                                airplane.setSeatStatus(airSeat.getSeatStatus());
                                airplane.setSettlePrice(airSeat.getSettlePrice());
                                airplane.setSeatCode(airSeat.getSeatCode());
                                airplane.setDiscount(airSeat.getDiscount());
                                airplane.setSeatMsg(airSeat.getSeatMsg());
                                airplane.setArriTime(airline.getArriTime());
                                airplane.setCompanyCode(airline.getFlightCompanyCode());
                                airplane.setContactName(airline.getFlightCompanyName());
                                airplane.setFrom(airline.getOrgCity());
                                airplane.setTo(airline.getDstCity());
                                airplane.setFlightNo(airline.getFlightNo());
                                airplane.setItemId(itemId);
                                airplane.setDepTime(airline.getDepTime());
                                airplane.setDstCityName(airline.getDstCityName());
                                airplane.setOrgCityName(airline.getOrgCityName());
                                airplane.setFlightCompanyName(airline.getFlightCompanyName());
                                airplaneList.add(airplane);
                            }
                        }
                    }
                } else {
                    for (int i = start; i < end; i++) {
                        Airline airline = airlinesLists.get(i);
                        List<AirSeat> seatList = airline.getAirSeats();
                        for (AirSeat airSeat : seatList) {
                            Airplane airplane = null;
                            if (airSeat.getSeatStatus() != null && airSeat.getSettlePrice() != null && airSeat.getSeatCode() != null && airSeat.getDiscount() != null && airSeat.getSeatMsg() != null) {
                                airplane = new Airplane();
                                airplane.setAdultAirportTax(airline.getAdultAirportTax());
                                airplane.setAdultFuelTax(airline.getAdultFuelTax());
                                airplane.setSeatStatus(airSeat.getSeatStatus());
                                airplane.setSettlePrice(airSeat.getSettlePrice());
                                airplane.setSeatCode(airSeat.getSeatCode());
                                airplane.setDiscount(airSeat.getDiscount());
                                airplane.setSeatMsg(airSeat.getSeatMsg());
                                airplane.setArriTime(airline.getArriTime());
                                airplane.setCompanyCode(airline.getFlightCompanyCode());
                                airplane.setContactName(airline.getFlightCompanyName());
                                airplane.setFrom(airline.getOrgCity());
                                airplane.setTo(airline.getDstCity());
                                airplane.setFlightNo(airline.getFlightNo());
                                airplane.setDepTime(airline.getDepTime());
                                airplane.setDstCityName(airline.getDstCityName());
                                airplane.setOrgCityName(airline.getOrgCityName());
                                airplane.setFlightCompanyName(airline.getFlightCompanyName());
                                airplaneList.add(airplane);
                            }
                        }
                    }
                }
            }
        } else {
            return ResultUtil.error(202, "已加载完毕");
        }
        sortListData(airplaneList);
        if (null != airplaneList && airplaneList.size() > 0) {
            return ResultUtil.success(airplaneList, "成功");
        } else {
            return ResultUtil.error(303, "未获取到数据");
        }
    }


    //查询单程飞机票
    public List<Airline> oddAirplane(String from, String fromDate, String to) throws Exception {
        AirLinesListRequest req = new AirLinesListRequest();
        itemId = findItemId();
        req.setFrom(from);
        req.setTo(to);
        req.setDate(fromDate);
        req.setItemId(itemId);
        AirLinesListResponse response = publicService.execute(req);
        List<Airline> airlinesList = response.getAirlines();
        return airlinesList;
    }

    /***
     * 排序飞机票数据集合
     * @param list
     */
    private void sortListData(List<Airplane> list) {
        MyComparactor mc = new MyComparactor();
        Collections.sort(list, mc);
    }

    class MyComparactor implements Comparator {

        @Override
        public int compare(Object o1, Object o2) {

            Airplane bean01 = (Airplane) o1;
            Airplane bean02 = (Airplane) o2;

            Double pri = bean01.getSettlePrice();
            Double pri02 = bean02.getSettlePrice();

            return pri.compareTo(pri02);
        }
    }


    public String[] createAliPayOrder(Long userId, String contactName, String contactTel, String date,
                                      String seatCode, String from, String to, String flightNo,
                                      String companyCode, String passagers, String depTime, String arriTime,
                                      String dstCityName, String orgCityName, String totalPayCash, String subject, String itemId) {

        User one = userRepository.findOne(userId);
        if (one == null) {
            throw new UserException("用户不存在", 202);
        }
//        totalPayCash = Base64Utils.getFromBase64(totalPayCash);//解密金额
        String[] res = new String[2];
        //支付宝生成订单
        AlipayOrder alipayOrder = new AlipayOrder();
        alipayOrder.setStoreId(one.getStoreId());
        alipayOrder.setSubject(subject);//对应的后台的信息
        String outTradeNo = "zyt" + userId + System.currentTimeMillis()   //添加userId
                + (long) (Math.random() * 10000000L);
        alipayOrder.setOutTradeNo(outTradeNo);
        alipayOrder.setTotalAmount(totalPayCash);
        alipayOrder.setUserId(userId);
        alipayOrder.setType(AlipayOrder.TYPE_AIRPLANE);
        alipayOrder.setOrderStatus(AlipayOrder.ORDER_WAIT);
        alipayOrderRepository.save(alipayOrder);

        //解析乘客信息
        int count = 0;
        try {
            JSONObject jsonObject = new JSONObject(passagers);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            JSONObject jsonObject1 = null;
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject1 = new JSONObject();
                jsonObject1 = jsonArray.getJSONObject(i);
                String phone = jsonObject1.getString("phone");
                String name = jsonObject1.getString("name");
//                String id = Base64Utils.getFromBase64(jsonObject1.getString("ID"));  //解密身份证
                String id = jsonObject1.getString("ID");  //解密身份证
                sb.append(name + "," + phone + "," + id);
                if (count >= 1) {
                    sb.append(";");
                }
                count++;
            }
            passagers = sb.substring(0, sb.length() - 1);
        } catch (JSONException e) {
            res[0] = "fail";
            res[1] = "创建订单失败";
            return res;
        }

        AirplaneRechargeOrder airplaneRechargeOrder = new AirplaneRechargeOrder();
        airplaneRechargeOrder.setPayType(BaseAirplaneAndTrianOrder.PAY_TYPE_ALIPAY);
        airplaneRechargeOrder.setPayResult(BaseAirplaneAndTrianOrder.STATUS_INIT);
        airplaneRechargeOrder.setUserId(userId);
        airplaneRechargeOrder.setOutTradeNo(outTradeNo);
        airplaneRechargeOrder.setContactName(contactName);
        airplaneRechargeOrder.setContactTel(contactTel);
        airplaneRechargeOrder.setStartStation(from);
        airplaneRechargeOrder.setRecevieStation(to);
        airplaneRechargeOrder.setDate(date);
        airplaneRechargeOrder.setSeatCode(seatCode);
        airplaneRechargeOrder.setItemId(itemId);
        airplaneRechargeOrder.setTotalPayCash(totalPayCash);
        airplaneRechargeOrder.setRecevieStation(dstCityName);
        airplaneRechargeOrder.setStartStation(orgCityName);
        airplaneRechargeOrder.setArriTime(arriTime);
        airplaneRechargeOrder.setDepTime(depTime);
        airplaneRechargeOrder.setFlightNo(flightNo);
        airplaneRechargeOrder.setPassagers(passagers);
        airplaneRechargeOrder.setCompanyCode(companyCode);
        airplaneRechargeOrder.setOrderCreateTime(new Date());
        airplaneRechargeOrder.setOrderType(BaseAirplaneAndTrianOrder.TYPE_AIR);
        airplaneRechargeOrderRepository.save(airplaneRechargeOrder);

        res[0] = "success";
        res[1] = alipayService.pay(alipayOrder) + "," + outTradeNo;
        return res;
    }

    public String[] createWxOrder(Long userId, String contactName, String contactTel, String date,
                                  String seatCode, String from, String to, String flightNo,
                                  String companyCode, String passagers, String depTime, String arriTime,
                                  String dstCityName, String orgCityName, String totalPayCash, String subject, String itemId, String ip) {

        User one = userRepository.findOne(userId);
        if (one == null) {
            throw new UserException("用户不存在", 202);
        }
//        totalPayCash = Base64Utils.getFromBase64(totalPayCash);//解密金额
        String outTradeNo = "zyt" + userId + System.currentTimeMillis()   //添加userId
                + (long) (Math.random() * 10000000L);
        String[] res = new String[2];
        WxPayOrder wxPayOrder = publicService.generateWxpayOrder(one, subject, ip, totalPayCash, outTradeNo, WxPayOrder.TYPE_AIRPLANE);
        wxPayOrderRepository.save(wxPayOrder);
        int count = 0;
        try {
            JSONObject jsonObject = new JSONObject(passagers);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            JSONObject jsonObject1 = null;
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject1 = new JSONObject();
                jsonObject1 = jsonArray.getJSONObject(i);
                String phone = jsonObject1.getString("phone");
                String name = jsonObject1.getString("name");
//                String id = Base64Utils.getFromBase64(jsonObject1.getString("ID"));  //解密身份证
                String id = jsonObject1.getString("ID");  //解密身份证
                sb.append(name + "," + phone + "," + id);
                if (count >= 1) {
                    sb.append(";");
                }
                count++;
            }
            passagers = sb.substring(0, sb.length() - 1);
        } catch (JSONException e) {
            res[0] = "fail";
            res[1] = "创建订单失败";
            return res;
        }

        AirplaneRechargeOrder airplaneRechargeOrder = new AirplaneRechargeOrder();
        airplaneRechargeOrder.setPayResult(BaseAirplaneAndTrianOrder.STATUS_INIT);
        airplaneRechargeOrder.setPayType(BaseAirplaneAndTrianOrder.PAY_TYPE_ALIPAY);
        airplaneRechargeOrder.setUserId(userId);
        airplaneRechargeOrder.setOutTradeNo(outTradeNo);
        airplaneRechargeOrder.setContactName(contactName);
        airplaneRechargeOrder.setContactTel(contactTel);
        airplaneRechargeOrder.setStartStation(from);
        airplaneRechargeOrder.setRecevieStation(to);
        airplaneRechargeOrder.setDate(date);
        airplaneRechargeOrder.setItemId(itemId);
        airplaneRechargeOrder.setSeatCode(seatCode);
        airplaneRechargeOrder.setTotalPayCash(totalPayCash);
        airplaneRechargeOrder.setRecevieStation(dstCityName);
        airplaneRechargeOrder.setStartStation(orgCityName);
        airplaneRechargeOrder.setArriTime(arriTime);
        airplaneRechargeOrder.setDepTime(depTime);
        airplaneRechargeOrder.setFlightNo(flightNo);
        airplaneRechargeOrder.setPassagers(passagers);
        airplaneRechargeOrder.setCompanyCode(companyCode);
        airplaneRechargeOrder.setOrderCreateTime(new Date());
        airplaneRechargeOrder.setOrderType(BaseAirplaneAndTrianOrder.TYPE_AIR);
        airplaneRechargeOrderRepository.save(airplaneRechargeOrder);

        res[0] = "success";
        res[1] = wxPayService.pay(wxPayOrder) + "," + outTradeNo;
        return res;
    }

    public String pay(String outTradeNo) {
        AirplaneRechargeOrder airplaneRechargeOrder = airplaneRechargeOrderRepository.findByOutTradeNo(outTradeNo);
        AirOrderCreateRequest req = new AirOrderCreateRequest();
        req.setItemId(airplaneRechargeOrder.getItemId());
        req.setContactName(airplaneRechargeOrder.getContactName());
        req.setContactTel(airplaneRechargeOrder.getContactTel());
        req.setDate(airplaneRechargeOrder.getDate());
        req.setFrom(airplaneRechargeOrder.getStartStation());
        req.setTo(airplaneRechargeOrder.getRecevieStation());
        req.setCompanyCode(airplaneRechargeOrder.getCompanyCode());
        req.setFlightNo(airplaneRechargeOrder.getFlightNo());
        req.setSeatCode(airplaneRechargeOrder.getSeatCode());
        req.setPassagers(airplaneRechargeOrder.getPassagers());

        try {
            AirOrderCreateResponse response = publicService.execute(req);
            if (response.isSuccess()) {
                airplaneRechargeOrder.setFailReason(response.getMsg());
                airplaneRechargeOrder.setPayResult(BaseAirplaneAndTrianOrder.STATUS_FAIL);
                airplaneRechargeOrderRepository.save(airplaneRechargeOrder);

                if (airplaneRechargeOrder.getPayType() == BaseAirplaneAndTrianOrder.PAY_TYPE_ALIPAY) {
                    AlipayOrder byOutTradeNo = alipayOrderRepository.findByOutTradeNo(outTradeNo);
                    byOutTradeNo.setRefundReason(response.getSubMsg());
                    return alipayService.reFund(byOutTradeNo);
                } else if (airplaneRechargeOrder.getPayType() == BaseAirplaneAndTrianOrder.PAY_TYPE_WXPAY) {
                    WxPayOrder wxPayOrder = wxPayOrderRepository.findByOutTradeNo(outTradeNo);
                    wxPayOrder.setRefundReason(response.getSubMsg());
                    return wxPayService.refund(wxPayOrder);
                }
            }
            //成功了操作。
            publicService.parseTicketOrderResponse(airplaneRechargeOrder, response.getTicketTrade());
            airplaneRechargeOrderRepository.save(airplaneRechargeOrder);
        } catch (ApiException e) {
            if (airplaneRechargeOrder.getPayType() == BaseQmOrder.PAY_TYPE_ALIPAY) {
                AlipayOrder byOutTradeNo = alipayOrderRepository.findByOutTradeNo(outTradeNo);
                byOutTradeNo.setRefundReason(e.getMessage());
                return alipayService.reFund(byOutTradeNo);
            } else if (airplaneRechargeOrder.getPayType() == BaseQmOrder.PAY_TYPE_WXPAY) {
                WxPayOrder wxPayOrder = wxPayOrderRepository.findByOutTradeNo(outTradeNo);
                wxPayOrder.setRefundReason(e.getMessage());
                return wxPayService.refund(wxPayOrder);
            }
            e.printStackTrace();
            throw new UserException("付款失败", 202);
        }
        return "error";
    }
}
